package cn.edu.zjicm.wordsnet_d.activity;

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import cn.edu.zjicm.wordsnet_d.R;
import cn.edu.zjicm.wordsnet_d.activity.FeedBackActivity.MyTextWatcher;
import cn.edu.zjicm.wordsnet_d.activity.base.BaseSlideActivity;
import cn.edu.zjicm.wordsnet_d.activity.base.WordBaseActivity;
import cn.edu.zjicm.wordsnet_d.datapersistent.AppPreference;
import cn.edu.zjicm.wordsnet_d.download.JudgeNetwork;
import cn.edu.zjicm.wordsnet_d.util.DateTimeUtils;
import cn.edu.zjicm.wordsnet_d.util.LogUtil;
import cn.edu.zjicm.wordsnet_d.util.StringUtil;
import cn.edu.zjicm.wordsnet_d.view.CircleImageView;

import com.umeng.fb.FeedbackAgent;
import com.umeng.fb.SyncListener;
import com.umeng.fb.model.Conversation;
import com.umeng.fb.model.Reply;
import com.umeng.fb.model.UserInfo;

import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v4.widget.SwipeRefreshLayout.OnRefreshListener;
import android.text.Editable;
import android.text.SpannableStringBuilder;
import android.text.Spanned;
import android.text.TextPaint;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.text.method.LinkMovementMethod;
import android.text.style.ClickableSpan;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.WindowManager;

import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

public class FeedBackForUMengActivity extends WordBaseActivity {

	private ListView mListView;
	private FeedBackForUMengActivity mContext;
	private TextView sendBtn;
	private EditText inputEdit;
	private SwipeRefreshLayout mSwipeRefreshLayout;

	private FeedbackAgent mAgent;
	private Conversation mComversation;
	private UserInfo userInfo;
	private ReplyAdapter adapter;

	private List<Reply> mReplyList;
	private Map<String, String> contactMap;

	private boolean showWelcomeInfo = false;

	private final int VIEW_TYPE_COUNT = 2;
	private final int VIEW_TYPE_USER = 0;
	private final int VIEW_TYPE_DEV = 1;
	private final int FEED_MAX_LEN = 10000;

	private static final int UPDATE = 0;
	private static final int CLOSE_REFRESH = 1;

	private long start;

	private Handler mHandler = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			switch (msg.what) {
			case UPDATE:
				adapter.notifyDataSetChanged();
				mListView.setSelection(ListView.FOCUS_DOWN);
				break;

			case CLOSE_REFRESH:
				mSwipeRefreshLayout.setRefreshing(false);
				Toast.makeText(mContext, "还没有新消息", Toast.LENGTH_SHORT).show();
				break;
			}

		}
	};

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_PAN);
		setContentView(R.layout.activity_feedback_umeng);
		mContext = this;

		setTitleBarStyle(TITLE_BAR_STYLE_BACK_BUTTON);
		setTitleText("意见反馈");

		setRightButton1("", R.drawable.fb_repeat, new OnClickListener() {

			@Override
			public void onClick(View v) {
				start = System.currentTimeMillis();
				mSwipeRefreshLayout.setRefreshing(true);
				sync(true);
			}
		});

		setBackButton(new OnClickListener() {

			@Override
			public void onClick(View v) {
				toFinish();
			}
		});

		findView();
		initView();
	}

	@Override
	protected void onResume() {
		super.onResume();
		AppPreference.setHasFeedback(mContext, false);
	}

	private void findView() {
		mListView = (ListView) findViewById(R.id.fb_reply_list);
		sendBtn = (TextView) findViewById(R.id.fb_send_btn);
		inputEdit = (EditText) findViewById(R.id.fb_send_content);
		mSwipeRefreshLayout = (SwipeRefreshLayout) findViewById(R.id.fb_reply_refresh);
	}

	private void initView() {
		mAgent = new FeedbackAgent(this);
		userInfo = mAgent.getUserInfo();
		if (userInfo == null) {
			userInfo = new UserInfo();
		}
		contactMap = userInfo.getContact();
		if (contactMap == null) {
			contactMap = new HashMap<String, String>();
		} else {
			String accountStr = AppPreference.getLoginID(this);
			if (accountStr != null) {
				if (AppPreference.getWeChatUnionid(this) != null) {
					contactMap.put("WX", accountStr);
				} else {
					contactMap.put("ZM", accountStr);
				}
			}
		}

		inputEdit.addTextChangedListener(new MyTextWatcher(inputEdit, FEED_MAX_LEN));
		inputEdit.setText(AppPreference.getSaveFeedback(mContext));

		mComversation = mAgent.getDefaultConversation();
		// mComversation.getReplyList()返回本地所有reply
		if (mComversation.getReplyList().size() == 0) {
			showWelcomeInfo = true;
			Calendar calendar = Calendar.getInstance();
			calendar.set(1970, 1, 1, 1, 1, 0);
			Reply reply = new Reply(getResources().getString(R.string.feedback_welcome_info), "1", "1", calendar.getTimeInMillis());
			reply.type = Reply.TYPE_DEV_REPLY;
			mComversation.getReplyList().add(0, reply);
		}

		adapter = new ReplyAdapter();
		mListView.setAdapter(adapter);
		mListView.setSelection(ListView.FOCUS_DOWN);
		sync(false);

		sendBtn.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				judgeCommit();
				// commit();
			}
		});

		// 下拉刷新
		mSwipeRefreshLayout.setOnRefreshListener(new OnRefreshListener() {
			@Override
			public void onRefresh() {
				sync(true);
			}
		});
	}

	protected void judgeCommit() {
		String content = inputEdit.getText().toString();
		/*
		 * if (StringUtil.calculateLength(content) < 10) { Toast.makeText(this,
		 * "输入内容少于5个字", Toast.LENGTH_SHORT).show();
		 * AppPreference.setSaveFeedback(mContext, content); } else
		 */
		if (!JudgeNetwork.getInstance(this).isWifiConnected() && !JudgeNetwork.getInstance(this).isMobileConnected()) {
			Toast.makeText(this, "网络未连接，提交失败，请稍后再试", Toast.LENGTH_SHORT).show();
			AppPreference.setSaveFeedback(mContext, content);
		} else {
			// if (AppPreference.isToadyFeedBack(this, DateTimeUtils.getDate())
			// && AppPreference.getFeedBackCount(this) >= 5) {
			// Toast.makeText(this, "提交次数过多，明天再来", Toast.LENGTH_SHORT).show();
			// AppPreference.setSaveFeedback(mContext, content);
			// } else {
			commit();
			// }
		}
	}

	private void commit() {
		String content = inputEdit.getText().toString();
		inputEdit.getEditableText().clear();
		if (!TextUtils.isEmpty(content)) {
			mComversation.addUserReply(content);// 添加到会话列表，并自动保存到SharedPreferences
			mHandler.sendMessage(new Message());
			sync(false);
			AppPreference.setSaveFeedback(mContext, "");
			// AppPreference.setFeedBackDate(this, DateTimeUtils.getDate());
			// AppPreference.setFeedBackCount(this);
		}

		userInfo.setContact(contactMap);
		mAgent.setUserInfo(userInfo);
		mAgent.updateUserInfo();
	}

	// 数据同步
	private void sync(final boolean showToast) {

		if (!JudgeNetwork.getInstance(FeedBackForUMengActivity.this).isWifiConnected()
				&& !JudgeNetwork.getInstance(FeedBackForUMengActivity.this).isMobileConnected()) {
			Toast.makeText(FeedBackForUMengActivity.this, "网络未连接，刷新失败", Toast.LENGTH_SHORT).show();
			mSwipeRefreshLayout.setRefreshing(false);
		} else {
			mComversation.sync(new SyncListener() {

				@Override
				public void onSendUserReply(List<Reply> replyList) {
					// replyList为本次同步数据中发送到服务器的用户反馈数据列表
					if (replyList != null && replyList.size() > 0) {
						mSwipeRefreshLayout.setRefreshing(false);
						mHandler.sendEmptyMessage(UPDATE);
					}
				}

				@Override
				public void onReceiveDevReply(List<Reply> replyList) {
					if (replyList != null && replyList.size() > 0) {
						mSwipeRefreshLayout.setRefreshing(false);
						mHandler.sendMessage(new Message());
					} else {
						if (showToast) {
							long delay = 3 * 1000 - (System.currentTimeMillis() - start);
							if (delay < 0) {
								delay = 0;
							}
							Message msg = new Message();
							msg.what = CLOSE_REFRESH;
							mHandler.sendMessageDelayed(msg, delay);
						}

					}
				}

			});
		}
	}

	class MyTextWatcher implements TextWatcher {

		EditText editText;
		int MAX_COUNT;

		public MyTextWatcher(EditText editText, int MAX_COUNT) {
			this.editText = editText;
			this.MAX_COUNT = MAX_COUNT;
		}

		@Override
		public void beforeTextChanged(CharSequence s, int start, int count, int after) {
		}

		@Override
		public void onTextChanged(CharSequence s, int start, int before, int count) {
			if (editText.getText().length() > 0) {
				sendBtn.setEnabled(true);
			} else {
				sendBtn.setEnabled(false);
			}
		}

		@Override
		public void afterTextChanged(Editable s) {
			int editStart = editText.getSelectionStart();
			int editEnd = editText.getSelectionEnd();

			// 先去掉监听器，否则会出现栈溢出
			editText.removeTextChangedListener(this);

			boolean toastHasShow = false;
			// 注意这里只能每次都对整个EditText的内容求长度，不能对删除的单个字符求长度
			while (StringUtil.calculateLength(s.toString()) > MAX_COUNT) { // 当输入字符个数超过限制的大小时，进行截断操作
				s.delete(editStart - 1, editEnd);
				editStart--;
				editEnd--;
				if (!toastHasShow) {
					Toast.makeText(FeedBackForUMengActivity.this, "意见反馈不能超过10000个字符", Toast.LENGTH_SHORT).show();
					toastHasShow = true;
				}
			}
			// mEditText.setText(s);将这行代码注释掉就不会出现后面所说的输入法在数字界面自动跳转回主界面的问题了，多谢@ainiyidiandian的提醒
			editText.setSelection(editStart);

			// 恢复监听器
			editText.addTextChangedListener(this);
		}

	}

	// adapter
	class ReplyAdapter extends BaseAdapter {

		@Override
		public int getCount() {
			return mComversation.getReplyList().size();
		}

		@Override
		public Object getItem(int arg0) {
			return mComversation.getReplyList().get(arg0);
		}

		@Override
		public long getItemId(int arg0) {
			return arg0;
		}

		@Override
		public int getViewTypeCount() {
			// 两种不同的Tiem布局
			return VIEW_TYPE_COUNT;
		}

		@Override
		public int getItemViewType(int position) {
			// 获取单条回复
			Reply reply = mComversation.getReplyList().get(position);
			if (Reply.TYPE_DEV_REPLY.equals(reply.type)) {
				// 开发者回复Item布局
				return VIEW_TYPE_DEV;
			} else {
				// 用户反馈、回复Item布局
				return VIEW_TYPE_USER;
			}
		}

		// holder需要为局部变量，不然会错乱
		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			final ViewHolder holder = new ViewHolder();
			final int p = position;
			// 获取单条回复
			Reply reply = mComversation.getReplyList().get(p);
			// if (convertView == null) {
			// 根据Type的类型来加载不同的Item布局
			if (Reply.TYPE_DEV_REPLY.equals(reply.type)) {
				// 开发者的回复
				convertView = LayoutInflater.from(mContext).inflate(R.layout.view_dev_reply, null);
			} else {
				// 用户的反馈、回复
				convertView = LayoutInflater.from(mContext).inflate(R.layout.view_user_reply, null);
			}

			// 创建ViewHolder并获取各种View
			holder.replyContent = (TextView) convertView.findViewById(R.id.fb_reply_content);
			holder.replyProgressBar = (ProgressBar) convertView.findViewById(R.id.fb_reply_progressBar);
			holder.replyStateFailed = (ImageView) convertView.findViewById(R.id.fb_reply_state_failed);
			holder.replyData = (TextView) convertView.findViewById(R.id.fb_reply_date);
			holder.portraitImg = (CircleImageView) convertView.findViewById(R.id.user_portrait);
			convertView.setTag(holder);

			if (position == 0 && reply.type.equals(Reply.TYPE_DEV_REPLY)) {
				String content = reply.content;
				int start = content.indexOf("点击此处");
				if (start != -1) {
					SpannableStringBuilder builder = new SpannableStringBuilder(content);
					builder.setSpan(new MyClickableSpan(), start, start + 9, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
					holder.replyContent.setText(builder);
					holder.replyContent.setFocusable(true);
					holder.replyContent.setMovementMethod(LinkMovementMethod.getInstance());
				} else {
					holder.replyContent.setText(content);
				}
			} else {
				holder.replyContent.setText(reply.content);
			}

			// 在App应用界面，对于开发者的Reply来讲status没有意义
			if (!Reply.TYPE_DEV_REPLY.equals(reply.type)) {
				// 根据Reply的状态来设置replyStateFailed的状态

				if (Reply.STATUS_NOT_SENT.equals(reply.status)) {
					holder.replyStateFailed.setVisibility(View.VISIBLE);
				} else {
					holder.replyStateFailed.setVisibility(View.GONE);
				}

				// 根据Reply的状态来设置replyProgressBar的状态
				if (Reply.STATUS_SENDING.equals(reply.status)) {
					holder.replyProgressBar.setVisibility(View.VISIBLE);
					postDelayed(p, holder);
				} else {
					holder.replyProgressBar.setVisibility(View.GONE);
				}

				setUserPortrait(holder.portraitImg);
			}

			holder.replyStateFailed.setOnClickListener(new OnClickListener() {

				@Override
				public void onClick(View v) {
					holder.replyStateFailed.setVisibility(View.GONE);
					holder.replyProgressBar.setVisibility(View.VISIBLE);
					sync(false);
					postDelayed(p, holder);
				}
			});

			// 回复的时间数据，这里仿照QQ两条Reply之间相差100000ms则展示时间
			// if ((position+1) < mComversation.getReplyList().size()) {
			Reply nextReply = mComversation.getReplyList().get(position);
			// if (nextReply.created_at - reply.created_at > 100000) {
			Date replyTime = new Date(reply.created_at);
			SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd  HH:mm:ss");
			holder.replyData.setText(sdf.format(replyTime));
			if (p > 0) {
				holder.replyData.setVisibility(View.VISIBLE);
			}
			// }
			// }
			return convertView;
		}

		public void setUserPortrait(CircleImageView portraitImg) {
			String headPortraitURL = AppPreference.getHeadPortrait(FeedBackForUMengActivity.this);
			if (headPortraitURL != null) {
				Uri imageUri = Uri.parse(headPortraitURL);
				portraitImg.setImageURI(null);
				portraitImg.setImageURI(imageUri);
			} else {
				portraitImg.setImageResource(R.drawable.head_portrait_default_gray);
			}
		}

		public void postDelayed(final int index, final ViewHolder holder) {
			mHandler.postDelayed(new Runnable() {
				@Override
				public void run() {
					updateview(index, holder);
				}
			}, 60000);
		}

		public void updateview(final int updateItemIndex, final ViewHolder holder) {

			Reply reply = mComversation.getReplyList().get(updateItemIndex);

			if (!Reply.TYPE_DEV_REPLY.equals(reply.type)) {
				// 根据Reply的状态来设置replyStateFailed的状态
				if (Reply.STATUS_NOT_SENT.equals(reply.status)) {
					holder.replyStateFailed.setVisibility(View.VISIBLE);
				} else {
					holder.replyStateFailed.setVisibility(View.GONE);
				}

				// 根据Reply的状态来设置replyProgressBar的状态
				if (Reply.STATUS_SENDING.equals(reply.status)) {
					holder.replyProgressBar.setVisibility(View.VISIBLE);
				} else {
					holder.replyProgressBar.setVisibility(View.GONE);
				}
			}
		}

		public View getViewByPosition(int position) {
			final int firstListItemPosition = mListView.getFirstVisiblePosition();
			final int lastListItemPosition = firstListItemPosition + mListView.getCount() - 1;
			if (position < firstListItemPosition || position > lastListItemPosition) {
				return mListView.getAdapter().getView(position, null, mListView);
			} else {
				final int childIndex = position - firstListItemPosition;
				return mListView.getChildAt(childIndex);
			}
		}

		class ViewHolder {
			TextView replyContent;
			ProgressBar replyProgressBar;
			ImageView replyStateFailed;
			TextView replyData;
			CircleImageView portraitImg;
		}
	}

	class MyClickableSpan extends ClickableSpan {

		@Override
		public void onClick(View widget) {
			Intent in = new Intent(FeedBackForUMengActivity.this, HelpCenterActivity.class);
			startActivity(in);
			toFinish();
		}

		@Override
		public void updateDrawState(TextPaint ds) {
			ds.setColor(getResources().getColor(R.color.tab_indicator_text_bg_down));
			ds.setUnderlineText(true);
		}
	}

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if (keyCode == KeyEvent.KEYCODE_BACK) {
			toFinish();
			return true;
		}
		return false;
	}

	public void toFinish() {
		finish();
		mContext = null;
	}
}
